from fastapi import APIRouter, UploadFile, File, HTTPException, Depends,Form
from pydantic import BaseModel
from typing import Optional, Dict, Any
from pathlib import Path
from utils.file_handler import save_temp_file, remove_temp_file
from utils.logger import setup_logger
from models.dependencies import get_dependencies
from data_handler.data_model_process import ModelHandler
from config import ModelConfig
from fastapi.responses import StreamingResponse

logger = setup_logger()

router_whisper = APIRouter(prefix="/whisper", tags=["Whisper"])

class WhisperConfig(BaseModel):
    language: Optional[str] = "auto"
    batch_size: int = 16
    align_output: bool = True
    custom_alignment_model: Optional[str] = None
    stream: bool = True

import json
from types import SimpleNamespace
import whisper

@router_whisper.post("/stream/transcribe")
async def whisper_stream_transcribe(
    audio: UploadFile = File(..., description="音频文件 (WAV/MP3格式)"),
    config: str = Form(...),
    dependencies: Dict[str, Any] = Depends(get_dependencies)
) -> StreamingResponse:
    """
    流式语音转录接口
    
    参数:
    - audio: 上传的音频文件
    - config: 转录配置参数
    - dependencies: 系统依赖项
    
    返回:
    - StreamingResponse: 流式转录结果
    """
    handler = ModelHandler()

    logger.info("语音转录开始")
    config = json.loads(config)
    if type(config) == dict:
        # 转对象
        config= SimpleNamespace(**config)

    logger.debug(f"Whisper 配置: {config.language} {config.stream}")

    try:
        # 1. 验证并保存上传文件
        logger.info(f"开始处理音频文件: {audio.filename}")
        if not audio.filename.lower().endswith(('.wav', '.mp3')):
            raise HTTPException(status_code=400, detail="仅支持WAV/MP3格式音频")
        
        temp_file_path = await save_temp_file(audio)
        logger.debug(f"临时文件保存路径: {temp_file_path}")

        # 2. 准备模型配置
        model_config = ModelConfig(
            model="whisper",
            temperature=0.0,
            max_tokens=512,
            stream=True,
            language=config.language,
            batch_size=config.batch_size,
            # align_output=config.align_output,
            # custom_alignment_model=config.custom_alignment_model
        )

        result = await handler.call_model(
            model="whisper",
            model_type="whisper",
            data=temp_file_path,
            streaming=True,
            config=model_config,
            dependencies=dependencies
        )
        
        if not result:
            raise HTTPException(status_code=500, detail="模型返回空结果")
            
        logger.info(f"流式转录完成 {result}")
        return result

    except HTTPException:
        raise  # 直接抛出已有的HTTP异常
    except Exception as e:
        logger.error(f"转录过程中发生错误: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"转录失败: {str(e)}")
    finally:
        # 清理资源
        try:
            if temp_file_path and Path(temp_file_path).exists():
                # remove_temp_file(temp_file_path)
                logger.debug(f"已清理临时文件: {temp_file_path}")
            # from models.model_manager import ModelManager
            # model_manager = ModelManager()
            # if model_manager:
            #     model_manager.decrement_usage("whisper")
            #     logger.debug("Whisper模型使用计数递减")
        except Exception as cleanup_error:
            logger.error(f"资源清理时发生错误: {str(cleanup_error)}", exc_info=True)